/*
 * Copyright (C) 2019 ByteDance Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bytedance.scene;


import ohos.aafwk.content.Intent;
import ohos.eventhandler.Courier;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.rpc.RemoteException;

/**
 * Created by JiangQi on 9/4/18.
 */
public class SingeProcessMessengerHandler {
    public static interface Callback {
        void onResult(Object result);
    }

    private static String EXTRA_TAG = "SingeProcessMessengerHandler";
    private Courier mMessenger;

    private SingeProcessMessengerHandler(Courier messenger) {
        this.mMessenger = messenger;
    }

    private static Courier createMessenger(final Callback callback) {
        return new Courier(new EventHandler(EventRunner.getMainEventRunner()){
            @Override
            protected void processEvent(InnerEvent event) {
                super.processEvent(event);
                callback.onResult(event.object);
            }
        });
    }

    public static void put(Intent intent, final Callback callback) {
        put(intent, callback, EXTRA_TAG);
    }

    public static void put(Intent intent, final Callback callback, String tagName) {
        Courier messenger = createMessenger(callback);
        intent.setParam(tagName, messenger);
    }

    public static SingeProcessMessengerHandler from(Intent intent) {
        return from(intent, EXTRA_TAG);
    }

    public static SingeProcessMessengerHandler from(Intent intent, String tagName) {
        Courier messenger = intent.getSequenceableParam(tagName);
        if (messenger != null) {
            return new SingeProcessMessengerHandler(messenger);
        } else {
            return null;
        }
    }

    public void sendResult(Object value) {
        InnerEvent innerEvent = InnerEvent.get();
        innerEvent.object = value;
        try {
            this.mMessenger.send(innerEvent);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}